const { friendList, User, friend_request } = require("../../../models")

// 处理好友请求
async function handleFriendRequest(io, socket, data, callback) {
    try {
        let req_doc = await friend_request
        .findById(data.applications_id)
        .populate({ 
            path:'sender receiver', 
            select: { phone: 1, nickname: 1, socketId: 1 }
        })
        
        if (!req_doc) {
            return callback({ 
                status_code: 404, 
                info: '该好友请求不存在或已被处理' 
            });
        }
        
        let sender = req_doc.sender.phone;
        let receiver = req_doc.receiver.phone;
        let senderNickname = req_doc.sender.nickname;

        let receiverFriends = await friendList.findOne({ phone: receiver }, { friends: 1 })
        let senderFriends = await friendList.findOne({ phone: sender }, { friends: 1 })
            
        let receiverDoc = await User.findOne({ phone: receiver })
        let senderDoc = await User.findOne({ phone: sender })

        if (data.status == 2) {     // 拒绝好友申请
            req_doc.status = 2;     // 将该条申请状态改为已拒绝，申请者和被申请者公用一个文档
            await req_doc.save();

            if (senderDoc.socketId) { // 通知申请者
                socket.to(senderDoc.socketId).emit("listen_friend_addResulst", { 
                    status_code: 403, 
                    applications_id: data.applications_id,
                    status: 2,
                    info: `${receiverDoc.nickname}拒绝了您的好友请求`
                })
            }

            // 改变接收者该条申请的状态
            callback({ 
                status_code: 403, 
                applications_id: data.applications_id, 
                status: 2,
                info: `已拒绝${senderNickname}的好友请求`
            })    

            return;
        }

        if (receiverFriends == null) {
            receiverFriends = new friendList({ phone: receiver, friends: [] })
            await receiverFriends.save()
        }
        if (senderFriends == null) {
            senderFriends = new friendList({ phone: sender, friends: [] })
            await senderFriends.save()
        }

        // 判断是否已经是好友
        if (!receiverFriends.friends.includes(senderDoc._id) && !senderFriends.friends.includes(receiverDoc._id)) {
            receiverFriends.friends.push({ friendId: senderDoc._id });
            senderFriends.friends.push({ friendId: receiverDoc._id });
            
            // 从发送者和接收者的applications数组中删除该申请ID
            await User.updateOne(
                { _id: senderDoc._id },
                { $pull: { applications: data.applications_id } }
            );
            
            await User.updateOne(
                { _id: receiverDoc._id },
                { $pull: { applications: data.applications_id } }
            );
            
            // 从数据库中删除该好友请求记录，而不是仅仅更新状态
            await friend_request.findByIdAndDelete(data.applications_id);

            await receiverFriends.save();
            await senderFriends.save();

            callback({ 
                status_code: 200,
                applications_id: data.applications_id,
                status: 1, 
                info: `已添加${senderNickname}为好友`
            })

            // 如果【发送者】在线则发送添加成功消息
            if (senderDoc.socketId) {
                socket.to(senderDoc.socketId).emit("listen_friend_addResulst", { 
                    status_code: 200,
                    applications_id: data.applications_id,
                    status: 1,
                    info: `${receiverDoc.nickname}已同意您的好友请求`,
                })
            }
        }
        else {
            callback({ status_code: 400, info: "已经是好友" })
        }
    } catch (error) {
        console.error('处理好友请求出错:', error);
        callback({ 
            status_code: 500, 
            info: '处理好友请求失败', 
            error: error.message 
        });
    }
}

module.exports = {
    handleFriendRequest,
}